const ConvModel = require('../model/conv.model')
const NewsModel = require('../model/news.model')
const UserModel = require('../model/user.model')
const RelationshipModel = require('../model/relationship.model')
const NotifyModel = require('../model/notify.model')
const { verifyToken } = require("../utils/jwt");
const logger = require('../utils/log4js')
const { verifyParams } = require('../utils/utils')
module.exports = {
    /**
     * 获取联系人列表
     */
    contactList: async (req, res) => {
        let token = req.headers.token
        let { data } = verifyToken(token)
        let list = await RelationshipModel.find({
            user: data._id
        }, '-__v -user').populate('visitor')
        // logger.info(list)
        list = list.map(item => {
            return {
                ...item.visitor,
                remarks: item.remarks
            }
        })
        return res.json({
            code: 1,
            data: list
        })
    },
    /**
     * 查找非好友用户列表
     */
    findNoFriendUsers: async (req, res) => {
        let verify = verifyParams(req.body, [
            {
                key: 'value',
                rule: [
                    { required: true },
                    { type: 'string' }
                ]
            }
        ])
        if (verify) res.json({ code: 0, msg: verify })

        const { value } = req.body
        let token = req.headers.token
        let { data } = verifyToken(token)

        // 排除自己
        let userList = await UserModel.find({
            email: {
                $in: [new RegExp(value, 'g')],
                $nin: [data.email]
            }
        }, '-pwd').lean()
        logger.info(2, userList)
        if (userList.length > 0) {
            const uIds = userList.map(item => {
                return item._id
            })
            // 排除好友
            let rel = await RelationshipModel.find({
                users: data._id,
                visitor: {
                    $nin: uIds
                }
            })

            if (rel.length > 0) {
                userList = userList.filter(item => {
                    return !rel.some(it => String(it.visitor) === String(item._id))
                })
                logger.info(1, userList)
            }
            // 已发送好友请求
            const notify = await NotifyModel.find({
                sender: data._id,
                recipient: uIds,
                type: '1',
                status: ['0', '2']
            })
            if (notify.length > 0) {
                userList = userList.map(item => {
                    let i = notify.findIndex(it => String(it.recipient) == String(item._id))
                    if (i > -1) {
                        item.status = notify[i].status // 0已发送好友请求。2已拒绝好友请求
                    } else {
                        item.status = undefined
                    }
                    return item
                })
                logger.info(0, userList)
            }
        }
        res.json({
            code: 1,
            data: userList
        })
    },
    /**
     * 发送好友请求
     */
    appendFriend: async (req, res) => {
        const { userId } = req.body
        let token = req.headers.token
        let { data } = verifyToken(token)
        // 是否已发送添加好友信息
        let result = await NotifyModel.findOne({
            sender: data._id,
            recipient: userId,
            type: '1',
            status: '0'
        }).lean()

        if (result) {
            res.json({
                code: 1,
                msg: '已发送请求。',
                data: result
            })
        } else {
            let sysMsg = new NotifyModel({
                sender: data._id,
                recipient: userId,
                text: '请求添加为好友。',
                type: '1'
            })
            await sysMsg.save()

            res.json({
                code: 1,
                msg: '已发送请求。',
                data: sysMsg
            })
        }
    },
    /**
     * 获取好友请求信息列表
     */
    appendFriendList: async (req, res) => {
        let token = req.headers.token
        let { data } = verifyToken(token)
        const result = await NotifyModel.find({
            recipient: data._id,
            type: '1',
            status: '0'
        }, '-__v -recipient').populate('sender').lean()
        res.json({
            code: 1,
            msg: '操作成功',
            data: result
        })
    },
    /**
     * 处理好友请求
     */
    confirmAppend: async (req, res) => {
        const { id, toId, status } = req.body
        let token = req.headers.token
        let { data } = verifyToken(token)
        // 处理消息，更新消息状态
        await NotifyModel.updateOne({
            _id: id
        }, {
            status
        }).lean()

        // 是否已为好友
        const userList = await RelationshipModel.find({
            user: data._id,
            visitor: toId
        })
        if (userList.length === 0) {
            const re1 = new RelationshipModel({
                user: data._id,
                visitor: toId
            })
            await re1.save()
            const re2 = new RelationshipModel({
                user: toId,
                visitor: data._id
            })
            await re2.save()
            res.json({
                code: 1,
                msg: '成功添加为好友'
            })
        } else {
            res.json({
                code: 1,
                msg: '该用户已是您的好友。'
            })
        }
    },
    /**
     * 删除好友
     */
    delFriend: async (req, res) => {
        const { id } = req.body
        let token = req.headers.token
        let { data } = verifyToken(token)
        await RelationshipModel.deleteOne({
            user: data._id,
            visitor: id
        })
        await RelationshipModel.deleteOne({
            user: id,
            visitor: data._id
        })
        res.json({
            code: 1,
            msg: '删除成功!'
        })
    }
}